package com.velvetantler.weather.utils

import android.content.Context
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.MapsInitializer
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.velvetantler.weather.WeatherGlobal

class LocationUtils {

    /**
     * 获取位置 经纬度
     */
    fun getLocation(context: Context, callback: () -> Unit) {
        // 更新隐私合规状态,需要在初始化地图之前完成
        MapsInitializer.updatePrivacyShow(context, true, true);
        // 更新同意隐私状态,需要在初始化地图之前完成
        MapsInitializer.updatePrivacyAgree(context, true);
        // 初始化定位客户端
        val locationClient = AMapLocationClient(context)
        // 初始化定位客户端的配置
        val setLocationOption = AMapLocationClientOption()
        setLocationOption.isOnceLocation = true // 只获取一次位置信息
        setLocationOption.isLocationCacheEnable = false // 不使用缓存
        locationClient.setLocationOption(setLocationOption)
        // 设置定位监听，定位回调处理逻辑
        locationClient.setLocationListener { location: AMapLocation? ->
            // 保存经纬度
            WeatherGlobal.setLatitude(location!!.latitude.toString())
            WeatherGlobal.setLongitude(location.longitude.toString())
            // 获取城市名称并保存
            getCityName(location.latitude, location.longitude, context, callback)
        }
        // 开始定位
        locationClient.startLocation()
    }

    fun getCityName(latitude: Double, longitude: Double, context: Context, callback: () -> Unit) {
        val geocodeSearch = GeocodeSearch(context)
        geocodeSearch.setOnGeocodeSearchListener(object :
            GeocodeSearch.OnGeocodeSearchListener {
            override fun onRegeocodeSearched(
                result: RegeocodeResult?,
                rCode: Int
            ) {
                // 通过坐标查地址的结果
                WeatherGlobal.setCityName(result!!.regeocodeAddress.city)
                callback()
            }

            override fun onGeocodeSearched(
                p0: GeocodeResult?,
                p1: Int
            ) {
                // 通过地址查座标的结果
            }
        })
        val point = LatLonPoint(latitude, longitude)
        val query = RegeocodeQuery(point, 50F, GeocodeSearch.AMAP)
        geocodeSearch.getFromLocationAsyn(query)
    }

}